package com.ld.common.filter;

import java.io.File;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

public class StyleFilter implements Filter {

    private static String STYLE_DIR = "";

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) arg0;
        HttpServletResponse res = (HttpServletResponse) arg1;

        String uri = req.getRequestURI().substring(req.getContextPath().length());
        // 过滤掉其他资源请求，只响应静态资源请求
        if (!StringUtils.isEmpty(STYLE_DIR) && uri.contains(".")) {
            String rootpath = req.getServletContext().getRealPath("");
            uri = uri.replace(STYLE_DIR + "/", "/"); // 防止已经添加目录的再次处理
            String jumpUri = STYLE_DIR + uri;
            String filePath = rootpath + jumpUri;
            File file = new File(filePath);
            if (file.exists()) { // 文件存在时跳转，不存在时仍然引用原路径
                req.getRequestDispatcher(jumpUri).forward(req, res);
                return;
            }
        }
        arg2.doFilter(arg0, arg1);
    }

    @Override
    public void init(FilterConfig fc) throws ServletException {
        ServletContext context = fc.getServletContext();
        STYLE_DIR = (String) context.getAttribute("styleDir"); // 以/开头
        if (STYLE_DIR == null) {
            STYLE_DIR = "";
        } else {
            STYLE_DIR = STYLE_DIR.replaceAll("/+", "/").trim(); // 处理多余的/
        }
    }

}
